/**
 * 用户信息
 * resendPage - 要重发消息的页面标识
 * userId - 当前登录用户id
 */ 
var UC = UC ? UC : new Object();
var homeUrl;

function showErrorMessage(text, title){
	var t = typeof(title) != 'undefined' && title != null ? title : '错误';
	showMessage(text, t, 'error');
}

function showInformationMessage(text, title){
	var t = typeof(title) != 'undefined' && title != null ? title : '提示';
	showMessage(text, t, 'info');
}

function showQuestionMessage(text, title){
	var t = typeof(title) != 'undefined' && title != null ? title : '确认';
	showMessage(text, t, 'question');
}

function showWarningMessage(text, title){
	var t = typeof(title) != 'undefined' && title != null ? title : '警告';
	showMessage(text, t, 'warning');
}

function showMessage(text, title, icon){
	$.messager.alert(title, text, icon);
}

function showConfirmMessage(text, callback, title){
	var t = typeof(title) != 'undefined' && title != null ? title : '确认';
	$.messager.confirm(t, text , callback);
}

function initDataGrid(jid, aurl, pageSize, pageList) {
	//console.log(aurl);
	var size = 30;
	var list = [ 20, 30, 40, 50 ];

	if (pageSize && pageSize > 0) {
		size = pageSize;
	}

	if (pageList) {
		list = pageList;
	}

	$(jid).datagrid({
		loadFilter : function(data) {
//			console.log(data);
			//debugger;
//			var json = JSON.parse(data);
			if (data.code == 0) {
				//debugger;
				var record = data.record;
				/*
				_.each(record.rows, function(element){
					element.editButton = '<a href="#" onclick="alert(1);">修改</a>';
				});
				*/
//				console.log(record);
				return record;
			} else {
				handleError(data.code);
				return "";
			}
		},
		url : aurl,
		pageSize : size,
		pageList : list,
		pagination : true,
		fit : true,
		singleSelect : false,
		method : 'post',
	});
	//debugger;
	//console.log('done init data grid');
}

function refreshDataGrid(jgridId){
	$(jgridId).datagrid('reload');
}

function searchDataGrid(jid, json) {
	//$(jid).datagrid('load', json);
	$(jid).datagrid('load', {query: JSON.stringify(json)});
}


function refreshDataGrid(jid, json){
	$(jid).datagrid('load', json);
}
//var index = 0;
function showAddDialog(jformId, jdlgId, title){
	$(jformId).form('clear');
	
	$(jdlgId).dialog({
		title: title ? title : '添加',
		modal: true
	});
	
	$(jdlgId).dialog('open');
}

function showEditDialog(jgridId, jformId, jdlgId, title, callback){
	var rows = $(jgridId).datagrid('getSelections');

	var flag = false;
	
	if(!rows || rows.length == 0){
		showWarningMessage('请选择要编辑的行');
	}else if(rows.length > 1){
		showWarningMessage('只能选择一行编辑');
	}else{
		flag = true;
		
		$(jformId).form('load',rows[0]);
		$(jdlgId).dialog({
			title: title ? title : '编辑',
			modal: true
		});
		$(jdlgId).dialog('open');
		
		(callback && typeof(callback) === "function") && callback(rows[0]);
	} 
	
	return flag;
}

function showCopyDialog(jgridId, jformId, jdlgId, title, callback){
	var rows = $(jgridId).datagrid('getSelections');

	var flag = false;
	
	if(!rows || rows.length == 0){
		showWarningMessage('请选择要复制的行');
	}else if(rows.length > 1){
		showWarningMessage('只能选择一行复制');
	}else{
		flag = true;
		
		$(jformId).form('load',rows[0]);
		$(jdlgId).dialog({
			title: title ? title : '复制',
			modal: true
		});
		$(jdlgId).dialog('open');
		
		(callback && typeof(callback) === "function") && callback(rows[0]);
	} 
	
	return flag;
}

function closeDialog(jdlgId) {
	$(jdlgId).dialog('close');
}

/**
 * 
 * @param jgridId
 * @param jformId
 * @param jdlgId
 * @param table
 * @param idColumnName table column name
 * @param callback
 * @returns
 */
function saveItem(config) {	
	var idColumnName = config.idColumnName ? config.idColumnName : 'id';
	url = 'save/' + idColumnName + '/' + config.table + '.json';

	//blockUI('正在保存...');
	
	$(config.jformId).form('submit', {
		url : url,
		//ajax: false,
		onSubmit : function() {
			var flag = $(this).form('validate');
			if(flag == true){
				//blockUI('正在保存...');
				//closeDialog(config.jdlgId);
			}
			
			return flag;
		},
		success : function(data) {
			//unblockUI();
			//console.log('save item data=' + data);
			var json = JSON.parse(data);
			if(json && json.code == 0){
				// TODO 对于某些浏览器，提交后会断开连接，导致回调无法完成
				//var view = JSON.parse(data);
				//console.log('view=[' + view + ']');
				//if (view.code == 0) {
					// save success
					closeDialog(config.jdlgId);
					refreshDataGrid(config.jgridId);
				//} else {
				//	showErrorMessage('保存失败');
				//	handleError(data.code);
				//}
				var callback = config.callback;
				(callback && typeof(callback) === "function") && callback();
			}else{
				//debugger;
				showErrorMessage(json.message);
				//closeDialog(config.jdlgId);
				//refreshDataGrid(config.jgridId);
			}
		},
		onLoadError: function(){
			//unblockUI();
		}
	});
}

/**
 * 
 * @param jgridId
 * @param table
 * @param idField 
 * @param softField
 * @param validator
 * @param callback
 * @returns
 */
//function deleteItem(jgridId, table, idColumn, softColumn, validator, callback){
function deleteItem(config, title){	
    var rows = $(config.jgridId).datagrid('getSelections');
    var idField = config.idField ? config.idField : 'id';
    	
    if(rows && rows.length > 0){
    	var validator = config.validator;
//    	debugger;
    	if(!validator || (validator && typeof(validator) === "function" && validator(rows[0]))){
			showConfirmMessage(title ? title : '是否删除所选项目？', function(r){
				if(r){
			        var ids = new Array();
			        for(var i = 0; i < rows.length; i++){
			        	var obj = rows[i];
//			        	console.log(obj);
			        	ids[i] = eval('obj.' + idField)
			        }
			        
			    	var criteria = {
			    		idField : idField,
			    		idValues : ids,
			    		softField : config.softField,
			    		softValue : config.softValue
			    	}
//			        console.log(criteria);
			    	
			    	$.ajax({
			    		type : "post",
			    		url : 'delete/' + config.table + '.json',
			    		data : JSON.stringify(criteria),
			    		contentType: 'application/json',
			    		async: false,
			    		success : function(data) {
			                if (data.code != 0){
			                	showErrorMessage('删除失败');
			                	handleError(data.code);
			                }else{
			                	refreshDataGrid(config.jgridId);
			                	var callback = config.callback;
			                	(callback && typeof(callback) === "function") && callback(rows[0]);
			                }
			    		},
			    		error: function(){
			    			showErrorMessage('网络连接错误');
			    		}
			    	});
			    }
			});
    	}
    }else{
    	showWarningMessage('请选择要删除的行');
    }
}

function clearCriteria(jparentId){
	_.each(['input', 'hidden', 'password', 'select', 'textarea'], function(item){
		$(jparentId).children().find(item).each(function(){
			$(this).val('');
		});
	});
/*	
	clearSpecificCriteria(jparentId, 'text');
	clearSpecificCriteria(jparentId, 'hidden');
	clearSpecificCriteria(jparentId, 'password');
	clearSpecificCriteria(jparentId, 'file');\
*/
}
/*
function clearSpecificCriteria(jparentId, type){
	var pattern = jparentId + ' :input[type=' + type + ']';
	var inputs = $(pattern);

	for(var i = 0; i < inputs.length; i++){
		inputs[i].value = '';
	}
}
*/
function clearInput(jinputId){
	$(jinputId).val('');
}

function checkAndPush(form, url){
	if(!form || !form.title){
		showErrorMessage('通知标题不能为空');
		return;
	}
	
	if(!form || !form.text){
		showErrorMessage("通知内容不能为空");
		return;
	}

	push(form, url);
}

function push(form, url){
	$.ajax({
		type : "post",
		url : url,
		//async: false,
		data : form,
		success : function(data) {
			//showInformationMessage('发送完毕');
		},
		error: function(){
			/*
			if(data && data.code != 0){
				handleError(data.code);
			}
			*/
		}
	});
	
	showInformationMessage('发送完毕');
}

function getIdDescOrder(){
	var order = new Object();
	order.name = 'id';
	order.order = 'desc';
	
	var orderBy = new Array();
	orderBy.push(order);
	
	return JSON.stringify(orderBy);
}

function downloadFile(form, msg){
	var url;
	var m = msg ? msg : '正在下载...';
	
	blockUI(m);
	
	$.ajax({
		url: 'file/export.json', 
		type: 'POST',
		async: false,
		data: form,
    	success: function(data) {
    		unblockUI();
	        if(data.code != 0){
	        	showErrorMessage('保存失败');
	        	handleError(data.code);
	        }else{
	        	url = data.url;
	        }
    	},
    	error: function(XMLHttpRequest, textStatus, errorThrown) {
    		unblockUI();
    		showErrorMessage('网络连接失败')
    	}
    });
	
	//console.log(url);
	//open(url);
	window.location.href = url;
}

function selectFile(jfileId, type, title, jqbarId){
	var t = title ? title : '导入数据会覆盖原有数据，是否继续？'
	//debugger;
	showConfirmMessage(t, function(r){
		if(r){
			if(jqbarId){
				clearCriteria(jqbarId);
			}
			var accept = type == 'Excel' ? 'application/vnd.ms-excel' : '.csv';
			$(jfileId).attr('accept', accept);
			$(jfileId).click();
		}
	});
}

function resetSelect(jselectId, data, valueName, textName, selectedValue, formatter){
	$(jselectId).empty();
	
	var count = data.menus.length;
	
	for(var i = 0; i < count; i++){
		var e = data.menus[i];
		var value = eval('e.' + valueName);
		var text = eval('e.' + textName);
		
		var displayText = text;
		if(formatter && typeof(formatter) === "function"){
			displayText = formatter(value, text);
		}else{
			displayText = text;
		}
		
		$(jselectId).append('<option value="'+ value + '">' + displayText + '</option>');
	}	
	
	//console.log('selected value ' + selectedValue);
	if(selectedValue){
		$(jselectId).val(selectedValue);
	}
}

function handleError(code){
//	debugger;
	if(code == 1003){
		//debugger;
		if(homeUrl){
			window.location.href = homeUrl;
		}else{
			window.location.href = 'index.dox';
		}
	}
}

function checkExistence2(table, msg, query){
	var valid = false;
	
	$.ajax({
		type : "post",
		url : 'sql/query.json',
		data : JSON.stringify(query),
		contentType: 'application/json',
		async: false,
		success : function(data) {
//			console.log(data);
			if(data.code == 0){
				if(data.count && data.count > 0){
					showErrorMessage(msg);
				}else{
					valid = true;
				}
			}else{
				showErrorMessage('校验错误');
			}
		},
		error: function(){
			showErrorMessage('网络连接错误');
		}
	});
	
	return valid;	
}

function checkExistence(table, msg, column, value){
	var valid = false;
	
	var query = {
		"table": table,
		"condition": "and",
		"fields": "count(*)",
		"items": [
		    {
		    	"field": column,
		    	"operator": "=",
		    	"value": value
		    }
		]
	};
	
	return checkExistence2(table, msg, query);
}

function getMonthFirstDate(){
	var today = new Date();
	var year = today.getYear() + 1900;
	var month = today.getMonth() + 1;

	return year + '-' + (month < 10 ? '0' + month : month) + '-01';
}

function getDate(date){
	//debugger;
	var dd = date;
	var year = dd.getYear() + 1900;
	var month = dd.getMonth() + 1;
	var date =  dd.getDate();
	
	month = month < 10 ? '0' + month : month;
	date = date < 10 ? '0' + date : date;
	
	return year + '-' + month + '-' + date;
}

function getDateTime(date){
	var dd = date;
	var hour = dd.getHours();
	var min = dd.getMinutes();
	var second =  dd.getSeconds();
	
	hour = hour < 10 ? '0' + hour : hour;
	min = min < 10 ? '0' + min : min;
	second = second < 10 ? '0' + second : second;
	
	return getDate(date) + ' ' + hour + ':' + min + ':' + second;
}

/**
 * 
 * @param jtableId
 * @param wysiwye what you see is what you export. true - export unhide fields; false - export all table fields
 * @returns {String}
 */
function getExportColumns(jgrid, wysiwye){
	var columns = '';
	
	jgrid.children().find('th').each(function(){
		//debugger;
		if(!$(this).attr('checkbox')){
			var options = $(this).attr('data-options');
			
			if(options){
				var option = eval("({" + options + "})");
				if(wysiwye){
					if(!option.hidden){
						columns = columns + option.field + ',' + $(this).text() + ';';
					}
				}else{
					columns = columns + option.field + ',' + $(this).text() + ';';
				}
			}
		}
	});
	
	//debugger;
	if(columns){
		columns = columns.substring(0, columns.length - 1);
	}
	
	return columns;
}

function blockUI(msg){
	//$.blockUI({ message: msg, baseZ:0}); 
	$.blockUI({ message: msg}); 
}

function blockUI(msg, zorder){
	//$.blockUI({ message: msg, baseZ:0}); 
	$.blockUI({ message: msg, baseZ:zorder}); 
}

function unblockUI(fadeOut){
	$.unblockUI({ fadeOut: fadeOut ? fadeOut : 0 });
}

function initUploadFileForm(jform, jcolumnMap, jgrid, wysiwye, callback){
//	debugger;
	var map = getExportColumns(jgrid, wysiwye);
	console.log(map);
	jcolumnMap.val(map);
	
	var jfile = jform.find('input[type="file"]');
	jfile.val('');
	
	var jiframe = jform.next('iframe');
	var name = jiframe.attr('name');
	jform.attr('target', name);
//	debugger;
	$('#' + name).load(function(){
//		debugger;
		unblockUI();
		
		jfile.val('');
		var text = jiframe.contents().children().find('pre').text();
		console.log('frame contents -> [' + text + ']');
		//debugger;
		if(text){
			var data = JSON.parse(text);
			console.log('import return data is ' + data);
			if(data && data.code == 0){
				refreshDataGrid('#' + jgrid.attr('id'));
//				debugger;
				(callback && typeof(callback) === "function") && callback();
				
				var msg = data.message ? data.message : '导入成功'; 
				showInformationMessage(msg);
				
			}else{
//				showErrorMessage('导入失败');
				var errMsg = '导入失败';
				if(data && data.message){
					errMsg = data.message;
				}
				showErrorMessage(errMsg);
			}
		}else{
			//showInformationMessage("登录超时，重新登录页面跳转中...");
			//handleError(1003);
		}
	});
}

function startUpload(jform, msg){
	//debugger;
	jform.find('input[type="submit"]').click();
	
	var m = msg ? msg : '正在上传...';
	blockUI(m);
}

function refreshHeader(userId){
	$.ajax({
		type: 'get',
		url: 'user/overview.json?userId=' + userId,
		//async: false,
		success: function(data){
//			console.log(data);
			var name = data.name ? data.name : data.loginName;
			$('#headbar_user_name').text(name);
			
			var desc = '';
			if(data.roles){
				_.each(data.roles, function(element){
					desc = desc + (element.roleDesc ? element.roleDesc : element.roleName) + '/';
				});
			}
			desc = desc.substring(0, desc.length - 1);
			
			$('#headbar_user_role').text('(' + desc + ')');
		}
	});
}

function datetimeFormatter(value, row, index){
	var text = value;
	
	if(value){
		var datetime = value ? value.split("+")[0] : "";
		
		var arr = datetime.split("T");
		var date = arr[0];
		var time = arr.length > 1 ? arr[1] : "";
		
		text = date + " " + time;
	}
	
	return text;	
}

/**
 * 格式化unix时间戳
 * @param seconds
 */
function unixTimestampFormatter(seconds){
	var unixTime = seconds * 1000;
	var date = new Date(unixTime);
	
	var year = date.getYear() + 1900;
	var month = formatToDualNumber(date.getMonth() + 1);
	var day = formatToDualNumber(date.getDate());
	var hours = formatToDualNumber(date.getHours());
	var mins = formatToDualNumber(date.getMinutes());
	var seconds = formatToDualNumber(date.getSeconds());
	
	return year + '-' + month + '-' + day + ' ' + hours + ':' + mins + ':' + seconds; 
}

function formatToDualNumber(value){
	return value < 10 ? '0' + value : value;
}

function fillSelectData(config){
	var url = config.url;
	if(config.query){
		var json = JSON.stringify(config.query);
		url = 'sql/plain/query.json?sql=' + json;
	}
	
	config.target.empty();
	
	$.ajax({
		type: 'post',
		url: url,
		data: json,
		dataType: 'json',
		async: false,
		success: function(data){
			//console.log(data);
			if(data && data.code == 0 && data.rows){
				for(var i = 0; i < data.rows.length; i++){
					//debugger;
					var value = config.value ? config.value(data.rows[i]) : '';
					var text = config.text ? config.text(data.rows[i]) : '';
					var attr = config.attr ? config.attr(data.rows[i]) : '';
					config.target.append('<option value="' + value + '"' + attr + '>' + text + '</option>');
				}
				
				if(config.postHandler){
					config.postHandler(data);
				}
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			config.error(XMLHttpRequest, textStatus, errorThrown);
		}
	});	
}